# 导入相关库
import sys

import requests
from PyQt5 import QtWidgets
from PyQt5.QtCore import QThread, pyqtSignal
from PyQt5.QtWidgets import QMainWindow, QDialog
from requests import Session
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FC
import matplotlib.pyplot as plt


# 导入创建的主窗口python类
from mainwindow import Ui_MainWindow
from childwindow import  Ui_Dialog

smoke_api_url = "http://api.nlecloud.com/devices/983980/sensors/m_smoke"
fans_api_url = "http://api.nlecloud.com/devices/983980/sensors/m_fan"
led_api_url = "http://api.nlecloud.com/devices/983980/sensors/m_lamp"
rgb_red_api_url = "http://api.nlecloud.com/devices/983980/sensors/rgb_red"
rgb_blue_api_url = "http://api.nlecloud.com/devices/983980/sensors/rgb_blue"
rgb_green_api_url = "http://api.nlecloud.com/devices/983980/sensors/rgb_green"
rgb_control_api_url = "http://api.nlecloud.com/Cmds"

multi_api_url = "http://api.nlecloud.com/devices/983980/Datas"

class MyDialog(QDialog):
    request : Session = None

    def __init__(self):
        QDialog.__init__(self)
        self.ui = Ui_Dialog()
        self.ui.setupUi(self)
        self.rgb_red = 0
        self.rgb_green = 0
        self.rgb_blue = 0
        self.ui.horizontalSlider_red.valueChanged.connect(self.callback_Slider_value_change)
        self.ui.horizontalSlider_blue.valueChanged.connect(self.callback_Slider_value_change)
        self.ui.horizontalSlider_green.valueChanged.connect(self.callback_Slider_value_change)
        self.initCharts()

    def initCharts(self):
        plt.rcParams['font.sans-serif'] = ['SimHei']
        self.fig = plt.figure()
        # self.fig = Figure()
        self.canvas = FC(self.fig)
        self.temp_axe = self.fig.add_subplot(221)
        self.humi_axe = self.fig.add_subplot(222)
        self.light_axe = self.fig.add_subplot(223)
        self.ui.verticalLayout.addWidget(self.canvas)


    def drawCharts(self, axe, title, xlabel, ylabel, x, y):
        print(x)
        print(y)
        axe.cla()
        axe.plot(x,y,marker='o',color='green')
        axe.set_title(title)
        axe.set_xlabel(xlabel)
        axe.set_ylabel(ylabel)
        axe.set_xticks(x)
        axe.set_xticklabels(x, rotation=30)
        axe.legend()

    def collect(self):
        self.cthread = CollectThread()
        self.cthread.request = self.request
        self.cthread.ui_update_signal.connect(self.ui_update_callback)
        self.cthread.start()

    def callback_Slider_value_change(self, value):
        self.rgb_red = self.ui.horizontalSlider_red.value()
        self.rgb_green = self.ui.horizontalSlider_green.value()
        self.rgb_blue = self.ui.horizontalSlider_blue.value()
        self.ui.label_rgb_state.setStyleSheet("background-color: rgb({}, {}, {});".format(self.rgb_red, self.rgb_green, self.rgb_blue))
        self.send_rgb_change()

    def send_rgb_change(self):
        self.cthread.control(rgb_control_api_url, '983980', 'rgb_red', self.rgb_red)
        self.cthread.control(rgb_control_api_url, '983980', 'rgb_blue', self.rgb_blue)
        self.cthread.control(rgb_control_api_url, '983980', 'rgb_green', self.rgb_green)

    def ui_update_callback(self, datas):
        if datas['m_smoke'] != "":
            val = datas['m_smoke']['ResultObj']['Value']
            if val == 0:
                self.ui.label_smoke_state.setText("关闭")
            else:
                self.ui.label_smoke_state.setText("开启")
        if datas['m_fan'] != "":
            val = datas['m_fan']['ResultObj']['Value']
            if val == 0:
                self.ui.label_fans_state.setText("关闭")
            else:
                self.ui.label_fans_state.setText("开启")
        if datas['m_lamp'] != "":
            val = datas['m_lamp']['ResultObj']['Value']
            if val == 0:
                self.ui.label_led_state.setText("关闭")
            else:
                self.ui.label_led_state.setText("开启")
        rgb = {}
        if datas['rgb_red'] != "":
            val = datas['rgb_red']['ResultObj']['Value']
            rgb['rgb_red'] = val
        if datas['rgb_blue'] != "":
            val = datas['rgb_blue']['ResultObj']['Value']
            rgb['rgb_blue'] = val
        if datas['rgb_green'] != "":
            val = datas['rgb_green']['ResultObj']['Value']
            rgb['rgb_green'] = val

        print("当前颜色rgb({},{},{})".format(rgb['rgb_red'], rgb['rgb_green'], rgb['rgb_blue']))
        self.ui.label_rgb_color.setText("当前颜色rgb({},{},{})".format(rgb['rgb_red'], rgb['rgb_green'], rgb['rgb_blue']))

        # print(type(datas['m_temperature']))
        if datas['m_temperature'] != "":
            vals = datas['m_temperature']['ResultObj']['DataPoints'][0]['PointDTO'][:5]
            vals.reverse()
            x = []
            y = []
            for dto in vals:
                x.append(dto['RecordTime'])
                y.append(dto['Value'])
            if float(y[0]) >= 25.0:
                self.cthread.control(rgb_control_api_url, '983980', 'm_fan', 1)
            else:
                self.cthread.control(rgb_control_api_url, '983980', 'm_fan', 0)
            self.drawCharts(self.temp_axe, "温度数据", "采集时间", "温度（单位℃）", x, y)

        if datas['m_humidity'] != "":
            vals = datas['m_humidity']['ResultObj']['DataPoints'][0]['PointDTO'][:5]
            vals.reverse()
            x = []
            y = []
            for dto in vals:
                x.append(dto['RecordTime'])
                y.append(dto['Value'])
            self.drawCharts(self.humi_axe, "湿度数据", "采集时间", "湿度（单位%RH）", x, y)

        if datas['m_light'] != "":
            vals = datas['m_light']['ResultObj']['DataPoints'][0]['PointDTO'][:5]
            vals.reverse()
            x = []
            y = []
            for dto in vals:
                x.append(dto['RecordTime'])
                y.append(dto['Value'])
            if float(y[0]) <= 150.0:
                self.cthread.control(rgb_control_api_url, '983980', 'm_lamp', 1)
            else:
                self.cthread.control(rgb_control_api_url, '983980', 'm_lamp', 0)
            self.drawCharts(self.light_axe, "光照数据", "采集时间", "光照度（单位Lux）", x, y)
        plt.tight_layout()
        self.canvas.draw()

class CollectThread(QThread):
    request: Session = None
    ui_update_signal = pyqtSignal(dict)
    dicts = {}

    def run(self):
        print("开始采集")
        while True:
            self.dicts['m_smoke'] = self.collect(smoke_api_url)
            self.dicts['m_fan'] = self.collect(fans_api_url)
            self.dicts['m_lamp'] = self.collect(led_api_url)
            self.dicts['rgb_green'] = self.collect(rgb_green_api_url)
            self.dicts['rgb_blue'] = self.collect(rgb_blue_api_url)
            self.dicts['rgb_red'] = self.collect(rgb_red_api_url)
            self.dicts['m_temperature'] = self.collect_multi(multi_api_url, 'm_temperature', 5)
            self.dicts['m_humidity'] = self.collect_multi(multi_api_url, 'm_humidity', 5)
            self.dicts['m_light'] = self.collect_multi(multi_api_url, 'm_light', 5)
            self.ui_update_signal.emit(self.dicts)
            self.sleep(3)

    def collect(self, url):
        response = self.request.get(url)
        if response.status_code == 200:
            print(response.json())
            if response.json()['Status'] == 0:
                return response.json()
            else:
                print("新大陆云 状态码", response.json()['ResultObj']['Status'])
                return ""
        else:
            print("http 状态码", response.status_code)
            return ""

    def collect_multi(self, url, apiTag, minago):
        get_params = {'ApiTags': apiTag, 'Method':1, 'TimeAgo':minago, 'Sort':'DESC'}
        response = self.request.get(url, params=get_params)
        if response.status_code == 200:
            print(response.json())
            if response.json()['Status'] == 0:
                return response.json()
            else:
                print("新大陆云 状态码", response.json()['ResultObj']['Status'])
                return ""
        else:
            print("http 状态码", response.status_code)
            return ""

    def control(self, url, deviceId, apiTag, cmds):
        post_params ={'deviceId': deviceId, 'apiTag': apiTag}
        response = self.request.post(url, params=post_params, json=cmds)
        if response.status_code == 200:
            print(response.json())
            if response.json()['Status'] == 0:
                return response.json()
            else:
                print("新大陆云 状态码", response.json()['ResultObj']['Status'])
                return ""
        else:
            print("http 状态码", response.status_code)
            return ""


class MyMainWindow(QMainWindow):
    '''
    自定义一个MyMainWindow类（继承了QMainWindow类）
    '''
    def __init__(self):
        '''
        初始化方法
        '''
        # 调用父类 `QMainWindow` 的初始化方法，确保父类的所有功能都被正确初始化。
        QMainWindow.__init__(self)
        # 创建一个 `Ui_MainWindow` 类的实例，并将其赋值给 `self.ui`。这个实例将用于设置窗口的界面
        self.ui = Ui_MainWindow()
        # 调用 `Ui_MainWindow` 实例的 `setupUi` 方法，并传入当前 `MyMainWindow` 类的实例作为参数。这个方法将设置窗口的属性和添加部件（如按钮、文本框等）。
        self.ui.setupUi(self)
        self.account : str = ""
        self.password : str = ""
        self.request = requests.Session()
        # self.setStyleSheet("#MainWindow{border-image: url(dabao.jpeg);}")
        self.ui.pushButton.clicked.connect(self.clicked_login)

    def clicked_login(self):
        self.account = self.ui.textEdit.toPlainText()
        self.password = self.ui.textEdit_2.toPlainText()
        print(self.account, "登录中")
        url = "https://api.nlecloud.com/Users/Login"
        login_data = {"Account" : self.account, "Password" : self.password}
        response = self.request.post(url=url, data=login_data)
        if response.status_code == 200:
            print(self.account, "登录成功")
            print(response.json())
            accesstoken = response.json()['ResultObj']['AccessToken']
            # print(accesstoken)
            token_header = {'AccessToken' : accesstoken}
            self.request.headers.update(token_header)
            self.cwin = MyDialog()
            self.cwin.request = self.request
            self.cwin.show()
            self.cwin.collect()
        else:
            print(self.account, "登录失败，错误码是", response.status_code)

# 主程序入口
if __name__ == '__main__':
    # 创建一个 `QApplication` 对象。在 PyQt5 中，每个 GUI 应用程序都需要一个 `QApplication` 对象。`sys.argv` 是一个从命令行传递给 Python 脚本的参数列表。
    app = QtWidgets.QApplication(sys.argv)
    # 创建一个 `MyMainWindow` 类的实例。
    mainWin = MyMainWindow()
    # 显示窗口
    mainWin.show()
    # 进入应用程序的主事件循环。这个方法会等待，直到应用程序关闭，然后返回一个退出代码。`sys.exit()` 确保一个干净的退出，返回 `app.exec_()` 的结果。
    sys.exit(app.exec_())